package com.zdkj.subway.epm.util;

import com.zdkj.admin.api.dto.UserInfo;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import lombok.experimental.UtilityClass;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @support: 
 * @author: cuilei
 * @version: 1.0
 * @Date: 2020-01-13 15:17:37.
 * @Description: <p>
 * <p>
 * 异常问题管理 set默认值  加入 线路 站点code
 * </p>
 */
@UtilityClass
public class ObjectFaultUtils {
   /**
    * 根据用户信息获取对应对象
    * @param cls
    * @param userInfo  用户信息
    * @return 转换后的对象
    */
	public <T> T getDefaultObj(Class<T> cls, UserInfo userInfo) {
        T obj = null;
        try {
            obj = cls.newInstance();
            setDefaultFiledValue(obj, userInfo);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }
    /**
     * 根据用户信息设置对象
     * @param obj  转换的对象
     * @param userInfo 用户信息
     */
    public void setDefaultFiledValue(Object obj, UserInfo userInfo) {
        Class clz = obj.getClass();
        PigxUser user = SecurityUtils.getUser();
        Map<String, Object> filedMap = new HashMap<String, Object>(5) {{
            if (null != userInfo) {
                put("creatorId", user.getId());
                put("creatorName", user.getNikeName());
                put("deptId", user.getDeptId());
                put("lineCode", userInfo.getSysUser().getLineCode());
                put("stationCode", userInfo.getSysUser().getStationCode());
            }
            put("createTime", LocalDateTime.now());
            put("delFlag", CommonConstants.STATUS_NORMAL);
        }};

        for (String filedName : filedMap.keySet()) {
            Field field;
            try {
                field = clz.getDeclaredField(filedName);
                field.setAccessible(true);
                field.set(obj, filedMap.get(filedName));
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } finally {
                continue;
            }
        }
    }
}
